<?php

namespace App\Server\API;

use App\Model\API\UserModel;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class RegisterService
{
    /**
     * 注册方法
     */
    public static function register($data)
    {
        //数据验证
        $rules = config('rules.register');
        $message = config('errorMessages.register');
        $validator = Validator::make($data,$rules,$message);
        foreach ($validator->errors()->all() as $v) {
            if (!empty($v)) {
                $code = config('errorCodes.register1.code');
                self::return_response($code,$v);
            }
        }
        //密码加密
        $rand_str = Str::random(4);
        $data['password'] = md5($data['password'] . $rand_str);
        $data['rand'] = $rand_str;
        //生成一个token
        $data['token'] = md5(uniqid());
        //存入数据库
        $result = UserModel::insertOne($data);
        if ($result) {
            $now = time();
            $encrypt_str = encrypt($data['token'] . '.' . $now);
            $content = json_encode(['email'=>$data['email'],'encrypt_str'=>$encrypt_str]);
            //发送邮件
            self::sendEmail($content,$data['email'],'账号激活','api.active_email');
            //返回响应信息提示注册成功，请打开邮件激活
            self::return_response(200,'邮件发送成功，请前往邮箱查看');
        }else{
            self::return_response(config('errorCodes.register2.code'),'业务繁忙，请稍候重试');
        }

    }
    /**
     * 返回响应的方法
     */
    public static function return_response($code,$message)
    {
        echo json_encode(['code'=>$code,'msg'=>$message],JSON_UNESCAPED_UNICODE);die;
    }
    /**
     * 发送邮件的方法
     * @param $content 发送的内容
     * @param $to 发送给谁
     * @param $subject 发送邮件的主题
     * @param $view 发送的页面
     */
    public static function sendEmail($content,$to,$subject,$view)
    {
        Mail::send(
            $view,
            ['content' => $content],
            function ($message) use ($to, $subject) {
                $message->to($to)->subject($subject);
            }
        );
        foreach (Mail::failures() as $v) {
            if (!empty($v)) {
                $code = config('errorCodes.sendEmail.code');
                self::return_response($code,$v);
            }
        }
    }
    /**
     * 账号激活
     */
    public static function activeEmail($data)
    {
        //数据验证--待补充
        //数据验证
        $rules = config('rules.activeEmail');
        $validator = Validator::make($data,$rules);
        if ($validator->errors()->all()) {
            return '无效的链接';
        }
        //验证邮箱
        $token = UserModel::selectOneField(['email'=>$data['email'],'status'=>1],'token');
        if ($token) {
            //激活程序
            $array = explode('.',decrypt($data['txt']));
            //判断是否过期
            if (time() - $array[1] > 3600 * 24  ) {
                return '链接已过期，请在一天内激活';
            }
            //判断token是否一致
            if ($token != $array[0]) {
                return '数据被篡改，激活失败';
            }
            //激活账户-同时更新token
            $result = UserModel::updateOne(['email'=>$data['email'],'status'=>'1'],['status'=>2,'token'=>Str::random(16)]);
            if ($result) {
                return '账户已激活';
            }else{
                return '业务繁忙，请稍候再试';
            }
        }else{
            //账户已激活，或者账户不存在
            return '该链接已失效';
        }

    }
}

